package com.xdwanj.gui;

import com.xdwanj.tools.DevelopmentMethod;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.*;
import java.util.List;

public class Model {

    //    普通变量
    private String abilityFlag = null;
    private File beforePath = null;
    private File overPath = null;
    private DevelopmentMethod tools = null;
    private boolean backFlag = false;
    private File backPath = null;
    private boolean countdownFlag = true;
    private int countdownVal = 0;

    //    面板
    private JFrame base = null;
    private Panel addressList = null;
    private Panel addressListLeft = null;
    private Panel addressListRight = null;
    private Panel abilityList = null;
    private Panel progress = null;
    private Panel operation = null;
    private JScrollPane scroll = null;

    //    组件
    private JTextField address_1 = null;
    private JTextField address_2 = null;
    private JButton addressBn_1 = null;
    private JButton addressBn_2 = null;
    private JComboBox ability = null;
    private JLabel status = null;
    private JLabel searchHint = null;
    private JTextField search = null;
    private JButton start = null;
    private JButton retract = null;
    private JButton init = null;
    private JTextArea traversing = null;
    private JProgressBar countdown = null;

    //构造方法，为一些比较复杂的变量赋值
    public Model() {
        tools = new DevelopmentMethod();
        launch();
    }

    //图形化界面的方法
    public void launch() {
//        框架初始化
        base = new JFrame("文件管理器");
        base.setLayout(null);
        base.setSize(750, 500);
        base.setLocationRelativeTo(null); //使软件的弹出位置为居中

//-------------第一部分（地址栏功能区部分）------------------------------------------------------
//------------宽度：710----高度：65------------------------------------------------------
        addressList = new Panel(null);
        addressList.setBounds(20, 20, 710, 65);

//        左边的面板
        addressListLeft = new Panel(new GridLayout(2, 1, 0, 15));
        addressListLeft.setSize(600, 65);

//        第一个地址栏
        address_1 = new JTextField();
        address_1.setTransferHandler(new MonitorAddress_1());

//        第二个地址栏
        address_2 = new JTextField();
        address_2.setTransferHandler(new MonitorAddress_2());

//        将组件加入面板
        addressListLeft.add(address_1);
        addressListLeft.add(address_2);
        addressListLeft.setVisible(true);

//        右边的面板
        addressListRight = new Panel(new GridLayout(2, 1, 0, 15));
        addressListRight.setBounds(610, 0, 90, 65);

//        第一个按钮
        addressBn_1 = new JButton("选择目录");
        addressBn_1.addActionListener(new MonitorAddressBn_1());

//        第二个按钮
        addressBn_2 = new JButton("选择目录");
        addressBn_2.addActionListener(new MonitorAddressBn_2());

//        将组件加入面板
        addressListRight.add(addressBn_1);
        addressListRight.add(addressBn_2);
        addressListRight.setVisible(true);

//        将面板加入面板
        addressList.add(addressListLeft);
        addressList.add(addressListRight);
        addressList.setVisible(true);

//-------------第二部分（功能区）------------------------------------------------------
//------------宽度：700----高度：50------------------------------------------------------
        operation = new Panel(null);
        operation.setBounds(20, 100, 700, 50);

//        状态标签
        status = new JLabel("状态栏");
        status.setBounds(10, 25, 70, 30);

        ability = new JComboBox();
        ability.setBounds(130, 0, 150, 50);
        ability.setBorder(BorderFactory.createTitledBorder("功能"));
        ability.addItem("复制到指定位置");
        ability.addItem("剪切到指定位置");
        ability.addItem("复制到U盘");
        ability.addItem("创建快捷方式");
        ability.setSelectedIndex(-1);
        ability.addActionListener(new MonitorAbility());

//        搜索标签
        searchHint = new JLabel("搜索框");
        searchHint.setBounds(300, 20, 70, 20);

//        搜索框
        search = new JTextField();
        search.setBounds(350, 15, 100, 30);
        search.addActionListener(new MonitorSearch());

//        开始按钮
        start = new JButton("开始");
        start.setBounds(460, 15, 70, 30);
        start.addActionListener(new MonitorStart());

//        撤销按钮
        retract = new JButton("撤销");
        retract.setBounds(540, 15, 70, 30);
        retract.addActionListener(new MonitorRetract());

//        清空按钮
        init = new JButton("清空");
        init.setBounds(620, 15, 70, 30);
        init.addActionListener(new MonitorInit());

//        将组件加入面板
        operation.add(status);
        operation.add(ability);
        operation.add(searchHint);
        operation.add(search);
        operation.add(start);
        operation.add(retract);
        operation.add(init);
        operation.setVisible(true);

//-------------第四部分（状态栏）------------------------------------------------------
//------------宽度：710----高度：300------------------------------------------------------
        progress = new Panel(null);
        progress.setBounds(20, 160, 710, 300);

//        状态框
        traversing = new JTextArea(8, 8);
        traversing.setLineWrap(true);

//        滚动框
        scroll = new JScrollPane(traversing);
        scroll.setBounds(0, 0, 700, 250);
        scroll.setVisible(true);

//        进度条
        countdown = new JProgressBar(0, 100);
        countdown.setStringPainted(true);
        countdown.setBounds(0, 260, 700, 25);

//        将组件加入面板
        progress.add(scroll);
        progress.add(countdown);
        progress.setVisible(true);

//------------框架组件添加区------------------------------------------------------------------------------------
        base.add(addressList);
        base.add(operation);
        base.add(progress);

//---------------框架末尾设置区-----------------------------------------------------------------------------------
        base.setVisible(true);
        base.setResizable(false);
        base.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

//----------------内部的方法--------------------------------------------------------------------------------

    //判断文件路径是否合法
    private boolean judgePath(File fileName) {
        if (fileName.exists()) {
            traversing.append("目录合法！" + "\n");
//            System.out.println("目录合法！");
            return true;
        } else {
            traversing.append("目录不合法！" + "\n");
//            System.out.println("目录不合法！");
            return false;
        }
    }

    //将字符串追加在JTextArea中
    private void promptWrite(String str) {
        traversing.append(str + "\n");
    }

    //上面那个的重载，遍历整个目录
    private void promptWrite(File val) {
        List<File> pathList = tools.getPathAll(val);

        for (File file : pathList) {
            promptWrite(file.toString());
        }
    }

    //建立一个新的线程，为进度条服务
    private void countdownAction() {
        Thread t = new CountdownThread();
        t.start();
    }

//----------------事件模型----------------------------------------------------------------------------------------

    //第一个文本框的拖拽事件
    private class MonitorAddress_1 extends TransferHandler {
        private static final long serialVersionUID = 1L;

        @Override
        public boolean importData(JComponent comp, Transferable t) {
            try {
                Object o = t.getTransferData(DataFlavor.javaFileListFlavor);

                String filepath = o.toString();
                if (filepath.startsWith("[")) {
                    filepath = filepath.substring(1);
                }
                if (filepath.endsWith("]")) {
                    filepath = filepath.substring(0, filepath.length() - 1);
                }
//                取到目录，将目录赋值给地址栏
                address_1.setText(filepath);
                promptWrite(filepath);
//                promptWrite("内容为：");
//                promptWrite("");
                return true;
            } catch (Exception e) {
//                未选择目录，捕获异常
                e.printStackTrace();
            }
            return false;
        }

        //        指示一个组件在实际尝试导入给定数据 flavor 的集合之前是否接受其导入
        @Override
        public boolean canImport(JComponent comp, DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                    return true;
                }
            }
            return false;
        }
    }

    //第二个文本框的拖拽事件,内部如上
    private class MonitorAddress_2 extends TransferHandler {
        private static final long serialVersionUID = 1L;

        @Override
        public boolean importData(JComponent comp, Transferable t) {
            try {
                Object o = t.getTransferData(DataFlavor.javaFileListFlavor);

                String filepath = o.toString();
                if (filepath.startsWith("[")) {
                    filepath = filepath.substring(1);
                }
                if (filepath.endsWith("]")) {
                    filepath = filepath.substring(0, filepath.length() - 1);
                }
                address_2.setText(filepath);
                overPath = new File(filepath);
                promptWrite(filepath);
//                promptWrite("内容为：");
//                promptWrite(new File(filepath));
//                promptWrite("");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public boolean canImport(JComponent comp, DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                    return true;
                }
            }
            return false;
        }
    }

    //第一个选择目录的操作
    private class MonitorAddressBn_1 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            jfc.showDialog(new JLabel(), "选择");
            File file = jfc.getSelectedFile();
            if (file.isDirectory()) {
                System.out.println("文件夹:" + file.getAbsolutePath());
                address_1.setText(file.toString());
            } else if (file.isFile()) {
                System.out.println("文件:" + file.getAbsolutePath());
                address_1.setText(file.toString());
            }
            promptWrite(file.toString());
//            promptWrite("内容为：");
//            promptWrite(new File(file.toString()));
//            promptWrite("");
        }
    }

    //第二个选择目录的操作
    private class MonitorAddressBn_2 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            jfc.showDialog(new JLabel(), "选择");
            File file = jfc.getSelectedFile();
            if (file.isDirectory()) {
                System.out.println("文件夹:" + file.getAbsolutePath());
                address_2.setText(file.toString());
            } else if (file.isFile()) {
                System.out.println("文件:" + file.getAbsolutePath());
                address_2.setText(file.toString());
            }
            promptWrite(file.toString());
//            promptWrite("内容为：");
//            promptWrite(new File(file.toString()));
//            promptWrite("");
        }
    }

    private class MonitorAbility implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int flag = ability.getSelectedIndex();

            switch (flag) {
                case 0:
                    abilityFlag = "Copy";
                    break;
                case 1:
                    abilityFlag = "Move";
                    break;
                case 2:
                    abilityFlag = "FlashDisk";
                    break;
                case 3:
                    abilityFlag = "Shortcuts";
                    break;
            }
        }
    }

    //搜索框回车事件
    private class MonitorSearch implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String str = null;
            List<File> pathList = null;

            str = search.getText();
            try {
                pathList = tools.FileFilters(new File(address_1.getText()), str);
            } catch (Exception o) {
                promptWrite("搜索框使用不规范！");
                promptWrite("");
                return;
            }

            if (pathList.size() == 0) {
                promptWrite("检索没有此内容！");
            } else {
                promptWrite("检索内容有：");
                for (File file : pathList) {
                    promptWrite(file.toString());
                }
            }
            promptWrite("");
        }
    }

    //按钮start的事件
    private class MonitorStart implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            beforePath = new File(address_1.getText());
            overPath = new File(address_2.getText());

            System.out.println(address_1.getText());
            System.out.println(address_2.getText());

            if (!judgePath(beforePath)) {
                return;
            }

            if ("FlashDisk".equals(abilityFlag)) {
                countdownFlag = true;
                countdownAction();
                backPath = tools.copyTOUSBDrive(beforePath);
                backFlag = true;
                countdownFlag = false;
                promptWrite("复制到U盘成功！");
            } else if ("Shortcuts".equals(abilityFlag)) {
                countdownFlag = true;
                countdownAction();
                try {
                    tools.createShortcuts(beforePath, search.getText());
                } catch (Exception o) {
                    promptWrite("当前没有选择文件类型，默认为“.exe”文件");
                    tools.createShortcuts(beforePath);
                }
                backFlag = false;
                countdownFlag = false;
                promptWrite("生成快捷方式成功！");
            } else if ("Copy".equals(abilityFlag)) {
                countdownFlag = true;
                countdownAction();
                if ("".equals(search.getText())) {
                    backPath = tools.copyAll(beforePath, overPath);
                } else {
                    backPath = tools.copyAll(beforePath, overPath, search.getText());
                }
                backFlag = true;
                countdownFlag = false;
                promptWrite("拷贝成功！");
            } else if ("Move".equals(abilityFlag)) {
                countdownFlag = true;
                countdownAction();
                tools.cutAll(beforePath, overPath);
                backFlag = false;
                countdownFlag = false;
                promptWrite("剪切成功！");
            } else {
                promptWrite("我不知道你干了什么！程序错误！");
                countdownFlag = false;
                backFlag = false;
            }
        }
    }

    //初始化的按钮
    private class MonitorInit implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            countdownFlag = false;
            abilityFlag = null;
            backFlag = false;
            address_1.setText("");
            search.setText("");
            address_2.setText("");
            traversing.setText("");
            ability.setSelectedIndex(-1);
            countdown.setValue(0);
            beforePath = null;
            overPath = null;
        }
    }

    //撤回的按钮
    private class MonitorRetract implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (!judgePath(backPath))
                    return;
            } catch (Exception o) {
                traversing.append("目录不合法！" + "\n");
                return;
            }

            if (backFlag) {
                countdownFlag = true;
                countdownAction();
                tools.deleteAll(backPath);
                countdownFlag = false;
                promptWrite("撤回成功！");
            } else {
                countdownFlag = false;
                promptWrite("撤回失败！无法撤回上一步操作！");
            }
        }
    }

    //开辟一个线程
    private class CountdownThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i <= 100; i++) {
                countdownVal = i;
                countdown.setValue(countdownVal);  //设置进度条的当前值
                if (!countdownFlag) {
                    i = 100;
                    countdownVal = 0;
                    countdown.setValue(100);
                }
                try {
                    Thread.sleep(500);      //堵塞500毫秒
                } catch (Exception o) {
                    o.printStackTrace();
                }
            }
        }
    }
}